package com.effectivsocial.core.i18n;

import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.inject.Named;

import lombok.extern.slf4j.Slf4j;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;

import org.omnifaces.util.Faces;
import org.omnifaces.util.Messages;



@Named
@Aspect
@Slf4j
public class MessagePopulatingControllerInterceptor {
	
	@AfterThrowing(pointcut = "@annotation(com.effectivsocial.core.i18n.I18nAware)", throwing = "error")
	public void logAfterThrowing(JoinPoint joinPoint, Throwable error) {
		String beanName = joinPoint.getTarget().getClass().getSimpleName();
		String actionName = joinPoint.getSignature().getName();
		String key = beanName + "." + actionName + "."
				+ error.getClass().getSimpleName() + ".ERROR";
		log.error("Error : {}", error.getLocalizedMessage());

		Messages.addGlobalError(key);
	}

	@AfterReturning(pointcut = "@annotation(com.effectivsocial.core.i18n.I18nAware)")
	public void logAfterReturning(JoinPoint joinPoint) {
		
		Boolean validationError = Faces.getFlashAttribute("validation.error");

		if (validationError == null || !validationError) {
			String beanName = joinPoint.getTarget().getClass().getSimpleName();
			String actionName = joinPoint.getSignature().getName();
			String key = beanName + "." + actionName + ".SUCCESS";

			
			Messages.addGlobalInfo(key);
		}
	}
	
	
}
